<?php
class Mwc_SystemPoint_UserpointController extends Mage_Adminhtml_Controller_Action{
	public function indexAction(){
		$this->loadLayout()
			->_addContent($this->getLayout()->createBlock('systempoint/userpoint_main'))
			->renderLayout();
//		$this->loadLayout();
//	    $this->getLayout()->getBlock('content')->append($this->getLayout()->createBlock('systempoint/userpoint_main'));
//	    $this->renderLayout();
    }
 
	public function deleteAction(){
        $userpointId = $this->getRequest()->getParam('id', false);
 
        try {
            Mage::getModel('systempoint/userpoint')->setId($userpointId)->delete();
            Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('systempoint')->__('User point successfully deleted'));
            $this->getResponse()->setRedirect($this->getUrl('*/*/'));
 
            return;
        } 
		catch (Exception $e){
            Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
        }
 
        $this->_redirectReferer();
    }
 
    public function newAction(){
        $this->loadLayout()
			->_addContent($this->getLayout()->createBlock('systempoint/userpoint_new'))
			->renderLayout();
    }
 
    public function postAction(){
        if ($data = $this->getRequest()->getPost()){
        	if($data['usertype']==1){        		
        		//scan to add point and send email to register
        		$collection = Mage::getResourceModel('customer/customer_collection');
			    $collection->addNameToSelect();
			    $collection->addFieldToFilter('email', array('like' => '%'.$data['emailformat'].'%'));
			    $collection->addAttributeToSelect('*');
//			    $collection->printLogQuery(true); 
			    $emaillist = explode(",", $data['otheremail']);
//			    $adddate = $data['add_date'];
//			    $expdate = $data['expire_date'];
			    try {
			    	if($emaillist[0]){
					    foreach ($emaillist as $otheremail){
					    	$itemid = 0;
					    	$upoint = 0;
			        		//check if exist and update point to related field
			        		$model = Mage::getModel('systempoint/userpoint');
			        		$userpoint = $model->getCollection()->addFieldToFilter('email', $otheremail);
							    foreach($userpoint as $item){
						            $itemid = $item->getUserpointId();
						            $upoint = $item->getUserPoint();
						        }
			        		if($itemid > 0){	
			        			if($upoint < $data['shadow_point']){
			        				$predata['user_point'] = $data['shadow_point'];
									$predata['shadow_point'] = $data['shadow_point'];
//									$predata['add_date'] = date('Y-m-d', strtotime($adddate));
//									$predata['exp_date'] = date('Y-m-d', strtotime($expdate));
			        			}
			        			$usrp = Mage::getModel('systempoint/userpoint')->load($itemid)->addData($predata);
			        			$usrp->setId($itemid)->save();
			        			
		        				$setting = Mage::getModel('systempoint/setting')->load(1);
					            $log = Mage::getModel('systempoint/log');
						        $log->setUserEmail($otheremail);
						        $log->setTitle($setting->getUpdatepointText());
						        $log->setPoint($data['shadow_point']);
						        $log->setLogDate(date('Y-m-d H:i:s', mktime()));
						        $log->save();
						        
			        			$mem = Mage::getModel('systempoint/membership')->loadHighestPoint();
		        				if($mem['number_of_point'] < $data['shadow_point']){
		        					$vipl = Mage::getModel('systempoint/viplist');
		        					$vipl->setEmail($otheremail);
		        					$vipl->setDate(date('Y-m-d H:i:s', mktime()));
		        					$vipl->save();
		        				}
			        			continue;
			        		}
							    $input['email'] = trim($otheremail);
								$input['user_point'] = $data['shadow_point'];						
								$input['group_title'] = $data['group_title'];
								$input['shadow_point'] = $data['shadow_point'];
//								$input['add_date'] = date('Y-m-d', strtotime($adddate));
//								$input['exp_date'] = date('Y-m-d', strtotime($expdate));
						    	$tip = Mage::getModel('systempoint/userpoint')->setData($input);
					            $tip->save();
					    
		        				$setting = Mage::getModel('systempoint/setting')->load(1);
					            $log = Mage::getModel('systempoint/log');
						        $log->setUserEmail($otheremail);
						        $log->setTitle($setting->getInitialText());
						        $log->setPoint($data['shadow_point']);
						        $log->setLogDate(date('Y-m-d H:i:s', mktime()));
						        $log->save();
						        
			        			$mem = Mage::getModel('systempoint/membership')->loadHighestPoint();
		        				if($mem['number_of_point'] < $data['shadow_point']){
		        					$vipl = Mage::getModel('systempoint/viplist');
		        					$vipl->setEmail($otheremail);
		        					$vipl->setDate(date('Y-m-d H:i:s', mktime()));
		        					$vipl->save();
		        				}
					            //create user and send email to invite
				        		$customer = Mage::getModel('customer/customer');
								//$customer  = new Mage_Customer_Model_Customer();
								//create password
				        		$len = 6;
								$base='ABCDEFGHKLMNOPQRSTWXYZabcdefghjkmnpqrstwxyz123456789';
								$max=strlen($base)-1;
								$activatecode='';
								mt_srand((double)microtime()*1000000);
								while (strlen($activatecode)<$len+1)
								$activatecode.=$base{mt_rand(0,$max)};
								//create user
								$customer->setWebsiteId(1);
								$customer->loadByEmail($otheremail);
								//Zend_Debug::dump($customer->debug()); exit;
								 
								if(!$customer->getId()) {								 
									$customer->setWebsiteId(1); 
									$customer->setStoreId(1); 
								    $customer->setEmail($otheremail);
								    $customer->setFirstname('User');
								    $customer->setLastname('Default');
								    $customer->setPassword($activatecode);
								}
								 
								try {
								    $customer->save();
								    $customer->setConfirmation(null);
								    $customer->save();
								 	$customer->sendNewAccountEmail();
								    //Make a "login" of new customer
//								    Mage::getSingleton('customer/session')->loginById($customer->getId());
								}
								 
								catch (Exception $ex) {
								    //Zend_Debug::dump($ex->getMessage());
								}
					    }
			    	}
	        		foreach ($collection as $row){	 
			        	//check if exist and update point to related field
			        	$itemid = 0;
			        	$upoint = 0;
		        		$model = Mage::getModel('systempoint/userpoint');
		        		$userpoint = $model->getCollection()->addFieldToFilter('email', $row->getEmail());
							    foreach($userpoint as $item){
						            $itemid = $item->getUserpointId();
						            $upoint = $item->getUserPoint();
						        }
		        		if($itemid > 0){		     	
		        			if($upoint < $data['shadow_point']){
		        				$predata['user_point'] = $data['shadow_point'];
								$predata['shadow_point'] = $data['shadow_point'];
//								$predata['add_date'] = date('Y-m-d', strtotime($adddate));
//								$predata['exp_date'] = date('Y-m-d', strtotime($expdate));
		        			}
		        			$usrp1 = Mage::getModel('systempoint/userpoint')->load($itemid)->addData($predata);
		        			$usrp1->setId($itemid)->save();
		        			
	        				$setting = Mage::getModel('systempoint/setting')->load(1);
				            $log = Mage::getModel('systempoint/log');
					        $log->setUserEmail($row->getEmail());
					        $log->setTitle($setting->getUpdatepointText());
					        $log->setPoint($data['shadow_point']);
					        $log->setLogDate(date('Y-m-d H:i:s', mktime()));
					        $log->save();
					        
		        			$mem = Mage::getModel('systempoint/membership')->loadHighestPoint();
	        				if($mem['number_of_point'] < $data['shadow_point']){
	        					$vipl = Mage::getModel('systempoint/viplist');
	        					$vipl->setEmail($row->getEmail());
	        					$vipl->setDate(date('Y-m-d H:i:s', mktime()));
	        					$vipl->save();
	        				}
		        			continue;
		        		}	  
					    $input['email'] = $row->getEmail();
						$input['user_point'] = $data['shadow_point'];						
						$input['group_title'] = $data['group_title'];
						$input['shadow_point'] = $data['shadow_point'];
//						$input['add_date'] = date('Y-m-d', strtotime($adddate));
//						$input['exp_date'] = date('Y-m-d', strtotime($expdate));
					    $tipusr = Mage::getModel('systempoint/userpoint')->setData($input);
			        	$tipusr->save(); 
			        	
        				$setting = Mage::getModel('systempoint/setting')->load(1);
			            $log = Mage::getModel('systempoint/log');
				        $log->setUserEmail($row->getEmail());
				        $log->setTitle($setting->getInitialText());
				        $log->setPoint($data['shadow_point']);
				        $log->setLogDate(date('Y-m-d H:i:s', mktime()));
				        $log->save();
				        
	        			$mem = Mage::getModel('systempoint/membership')->loadHighestPoint();
        				if($mem['number_of_point'] < $data['shadow_point']){
        					$vipl = Mage::getModel('systempoint/viplist');
        					$vipl->setEmail($row->getEmail());
        					$vipl->setDate(date('Y-m-d H:i:s', mktime()));
        					$vipl->save();
        				}
				    }
	                Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('systempoint')->__('User point successfully updated'));
	                $this->getResponse()->setRedirect($this->getUrl('*/*/'));
	                return;
		            } 
				catch (Exception $e){
	                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
	            }
        	}else{
        		//send email invite to register
			    $emaillist = explode(",", $data['newemail']);
        		try {
			    	if($emaillist[0]){
					    foreach ($emaillist as $otheremail){
					    	$itemid = 0;
					    	$upoint = 0;
			        		//check if exist and update point to related field
			        		$model = Mage::getModel('systempoint/userpoint');
			        		$userpoint = $model->getCollection()->addFieldToFilter('email', $otheremail);
							    foreach($userpoint as $item){
						            $itemid = $item->getUserpointId();
						            $upoint = $item->getUserPoint();
						        }
				        		if($itemid > 0){	
				        			if($upoint < $data['shadow_point']){
				        				$predata['user_point'] = $data['shadow_point'];
										$predata['shadow_point'] = $data['shadow_point'];
//										$predata['add_date'] = date('Y-m-d', strtotime($adddate));
//										$predata['exp_date'] = date('Y-m-d', strtotime($expdate));
				        			}
				        			$usrp = Mage::getModel('systempoint/userpoint')->load($itemid)->addData($predata);
				        			$usrp->setId($itemid)->save();
				        			
	        						$setting = Mage::getModel('systempoint/setting')->load(1);
						            $log = Mage::getModel('systempoint/log');
							        $log->setUserEmail($otheremail);
							        $log->setTitle($setting->getUpdatepointText());
							        $log->setPoint($data['shadow_point']);
							        $log->setLogDate(date('Y-m-d H:i:s', mktime()));
							        $log->save();
							        							        
        							$mem = Mage::getModel('systempoint/membership')->loadHighestPoint();
        							if($mem['number_of_point'] < $data['shadow_point']){
        								$vipl = Mage::getModel('systempoint/viplist');
        								$vipl->setEmail($otheremail);
        								$vipl->setDate(date('Y-m-d H:i:s', mktime()));
        								$vipl->save();
        							}
				        			continue;
				        		}
							    $input['email'] = trim($otheremail);
								$input['user_point'] = $data['shadow_point'];						
								$input['group_title'] = $data['group_title'];
								$input['shadow_point'] = $data['shadow_point'];
//								$input['add_date'] = date('Y-m-d', strtotime($adddate));
//								$input['exp_date'] = date('Y-m-d', strtotime($expdate));
						    	$tip = Mage::getModel('systempoint/userpoint')->setData($input);
					            $tip->save();
					            
        						$setting = Mage::getModel('systempoint/setting')->load(1);
					            $log = Mage::getModel('systempoint/log');
						        $log->setUserEmail($otheremail);
						        $log->setTitle($setting->getInitialText());
						        $log->setPoint($data['shadow_point']);
						        $log->setLogDate(date('Y-m-d H:i:s', mktime()));
						        $log->save();
						        
					    		$mem = Mage::getModel('systempoint/membership')->loadHighestPoint();
        						if($mem['number_of_point'] < $data['shadow_point']){
        							$vipl = Mage::getModel('systempoint/viplist');
        							$vipl->setEmail($otheremail);
        							$vipl->setDate(date('Y-m-d H:i:s', mktime()));
        							$vipl->save();
        						}
					            //create user and send email to invite
				        		$customer = Mage::getModel('customer/customer');
								//$customer  = new Mage_Customer_Model_Customer();
								//create password
				        		$len = 6;
								$base='ABCDEFGHKLMNOPQRSTWXYZabcdefghjkmnpqrstwxyz123456789';
								$max=strlen($base)-1;
								$activatecode='';
								mt_srand((double)microtime()*1000000);
								while (strlen($activatecode)<$len+1)
								$activatecode.=$base{mt_rand(0,$max)};
								//create user
								$customer->setWebsiteId(1);
								$customer->loadByEmail($otheremail);
								//Zend_Debug::dump($customer->debug()); exit;
								 
								if(!$customer->getId()) {								 
									$customer->setWebsiteId(1); 
									$customer->setStoreId(1); 
								    $customer->setEmail($otheremail);
								    $customer->setFirstname('User');
								    $customer->setLastname('Default');
								    $customer->setPassword($activatecode);
								}
								 
								try {
								    $customer->save();
								    $customer->setConfirmation(null);
								    $customer->save();
								 	$customer->sendNewAccountEmail();
								    //Make a "login" of new customer
//								    Mage::getSingleton('customer/session')->loginById($customer->getId());
								}
								 
								catch (Exception $ex) {
								    //Zend_Debug::dump($ex->getMessage());
								}
					    }
			    	}
        	
	                Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('systempoint')->__('User point successfully updated'));
	                $this->getResponse()->setRedirect($this->getUrl('*/*/'));
	                return;
		            } 
				catch (Exception $e){
	                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
	            }
        	}
        }
        $this->getResponse()->setRedirect($this->getUrl('*/*/'));
		
        return;
    }
    
    public function editAction(){
        $this->loadLayout();
        $this->_addContent($this->getLayout()->createBlock('systempoint/userpoint_edit'));
        $this->renderLayout();
    }
 
    public function saveAction(){
        $tipId = $this->getRequest()->getParam('id', false);
        if ($data = $this->getRequest()->getPost()) {
            try {
            	$model = Mage::getModel('systempoint/userpoint');
//			    $adddate = $data['add_date'];
//			    $expdate = $data['expire_date'];
        		$userpoint = $model->getCollection()->addFieldToFilter('userpoint_id', $tipId);
					    foreach($userpoint as $item){
				            $upoint = $item->getUserPoint();
				        }
        		if($upoint < $data['shadow_point']){
        			$predata['user_point'] = $data['shadow_point'];
					$predata['shadow_point'] = $data['shadow_point'];
//					$predata['add_date'] = date('Y-m-d', strtotime($adddate));
//					$predata['exp_date'] = date('Y-m-d', strtotime($expdate));
        		}
        		$tips = Mage::getModel('systempoint/userpoint')->load($tipId)->addData($predata);
                $tips->setId($tipId)->save();
 
        		$setting = Mage::getModel('systempoint/setting')->load(1);
	            $log = Mage::getModel('systempoint/log');
		        $log->setUserEmail($data['email']);
		        $log->setTitle($setting->getUpdatepointText());
		        $log->setPoint($data['shadow_point']);
		        $log->setLogDate(date('Y-m-d H:i:s', mktime()));
		        $log->save();
		        
                $mem = Mage::getModel('systempoint/membership')->loadHighestPoint();
				if($mem['number_of_point'] < $data['shadow_point']){
					$vipl = Mage::getModel('systempoint/viplist');
					$vipl->setEmail($data['email']);
					$vipl->setDate(date('Y-m-d H:i:s', mktime()));
					$vipl->save();
				}
				
                Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('systempoint')->__('User point successfully updated'));
                $this->getResponse()->setRedirect($this->getUrl('*/*/'));
                return;
            }
			catch (Exception $e){
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
            }
        }
        $this->_redirectReferer();
    }
}